package com.pattern.beforeclass.proxy;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Ping
 * @date 2022/4/18 10:29
 **/
public class FlyweightSaomeExample {
    public static void main(String args[]) {
        String key = "FUZHOU_XIAMEN_10" ;
        TicketDAO ticketDAO = new TicketDAO() ;

        for (int i=0; i<1000000000; i++) {
            ticketDAO.query(key);
        }
        System.out.println("END") ;


    }
}
interface ITicket {
    public String showInfor() ;
}
class TicketFromToInfor {
    String key ;
    String from ;
    String to ;
    String time ;

    public TicketFromToInfor(String key, String from, String to, String time) {
        this.key = key;
        this.from = from;
        this.to = to;
        this.time = time;
    }

}
class TicketFWFactory {
    static Map<String, TicketFromToInfor> ticketInforMap = new ConcurrentHashMap<>() ;
    static {
        ticketInforMap.put("FUZHOU_XIAMEN_10", new TicketFromToInfor("FUZHOU_XIAMEN_10", "FUZHOU", "XIAMEN", "10")) ;
    }
    public static TicketFromToInfor getTicket(String key) {
        return ticketInforMap.get(key) ;
    }

 }
class TicketFlyweight implements ITicket {
    private TicketFromToInfor ticketInnerState ;
    int left ;
    private String infor ;

    public TicketFlyweight(TicketFromToInfor ticketInnerState, int left) {
        this.ticketInnerState = ticketInnerState;
        this.left = left;

    }

    public void setTicketInnerState(TicketFromToInfor ticketInnerState) {
        this.ticketInnerState = ticketInnerState;
    }

    public void setLeft(int left) {
        this.left = left;
    }

    @Override
    public String showInfor() {
        return "[FROM : " + ticketInnerState.from +
                ", TO:" +ticketInnerState.to +
                ", LEFT: " +this.left +
                "]" ;

    }
}
class TicketBasicInfor implements ITicket {
    private String key ;
    private String from ;
    private String to ;
    private String time ;
    private int left ;

    public TicketBasicInfor(String from, String to, String time, int left) {
        this.key = from + "_" + to + "_" + time ;
        this.from = from;
        this.to = to;
        this.time = time;
        this.left = left;
    }
    @Override
    public String showInfor() {
        return "[FROM : " + from +
                ", TO:" +to +
                ", LEFT: " +this.left +
                "]" ;
    }
}

class TicketDAO {
    static Random Rand = new Random() ;
    public TicketBasicInfor query(String key) {
        String[] elements = key.split("_") ;
        return new TicketBasicInfor(elements[0], elements[1], elements[2], Rand.nextInt(100)) ;
    }
    public ITicket queryByFW(String key) {
        return new TicketFlyweight(TicketFWFactory.getTicket(key), Rand.nextInt(100)) ;
    }
}

interface NetworkDevice {
    public void use() ;
}



